﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoAllocService.Services.Enums;
using AutoAllocService.Services.Models;
using log4net;
using Newtonsoft.Json;

namespace AutoAllocService.Services
{
    public class AllocTaskPool : List<AllocTask>
    {
        private readonly object _lock = new object();
        private readonly ILog _log = LogManager.GetLogger(typeof(AllocTaskPool));

        public void StartTask(string json)
        {
            try
            {
                var model = JsonConvert.DeserializeObject<MqTaskModel>(json);
                if (model.Type == "assign")
                {
                    foreach (var modelBooking in model.Bookings)
                    {
                        lock (_lock)
                        {
                            if (CheckRunning(modelBooking.BookingID))
                                continue;
                            _log.Info($"Handle Booking {modelBooking.BookingID}");

                            var allocTask = new AllocTask(modelBooking);

                            var task = new System.Threading.Tasks.Task(async () =>
                            {
                                await allocTask.Start();
                                Remove(allocTask);
                                allocTask.Dispose();
                            });
                            Add(allocTask);
                            task.Start();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        private bool CheckRunning(string bookingId)
        {
            var task = this.FirstOrDefault(x => x.BookingID == bookingId);
            if (task == null) return false;
            if (task.Status == TaskStatus.Pending || task.Status == TaskStatus.Running)
                return true;
            Remove(task);
            task.Dispose();
            return false;
        }
    }
}
